<template>
<div>
  <div :id="idText"></div>
</div>

</template>
<script>

import {makeId} from '@/utils'

export default {
  name: 'SimplifyTinymce',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    value: {
      type: String,
    },
    disabled: {
      type: Boolean,
      default: false
    },
  },
  data () {
    return {
      idText: makeId('tinymce'),
      tinymceHtml: '',
      editor: null,
      initValue: true,
      tinyConfig: {
        relative_urls: false,
        convert_urls: false,
        language: 'zh_CN',
        width: 600,
        height: 300,
        toolbar_mode: 'sliding',
        content_style: "img {max-width:100%;}",
        plugins: false,
        toolbar: 'fullscreen preview | undo redo removeformat | bold italic underline strikethrough superscript subscript  | fontsizeselect forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist table | outdent indent blockquote | link unlink image axupimgs media code',
        paste_data_images: true,
        
        // statusbar: true, // 底部的状态栏
        // menubar: true, // 最上方的菜单
        // toolbar: true, // 最上方的菜单
        branding: false // 水印“Powered by TinyMCE”
      }
    }
  },
  watch: {
    value: {
      immediate: true,
      handler (newValue) {
        if (!this.initValue) return // 仅第一次赋值使用
        newValue = newValue || ''
        if (newValue) {
          this.initValue = false
          if (this.editor) {
            this.editor.setContent(newValue)
          }
        }
      }
    }
  },
  mounted () {
    this.$nextTick(()=> {
      this.initTinymce()
    })
  },
  methods: {
    initTinymce () {
      if (this.editor) return 
      const that = this
      this.tinyConfig.selector = `#${this.idText}`
      this.tinyConfig.init_instance_callback = (editor)=> {
        that.editor = editor
        editor.setContent(this.value || '')
        editor.on('change',function(){
          that.initValue = false
          that.$emit('change', editor.getContent())
          that.$emit('input', editor.getContent())
        })
      }
      tinymce.init(this.tinyConfig)
    },
  },
  beforeDestroy() {
    tinymce.remove(`#${this.idText}`)
  },
}
</script>